'''
版权：Copyright (c) 2019 China

创建日期：Thursday August 15th 2019
创建者：ymq(ymq) - <<email>>

修改日期: Thursday, 15th August 2019 3:55:23 pm
修改者: ymq(ymq) - <<email>>

说明
 1、财务账务管理（不涉及记账凭证，会计科目等）
 2、主要是收费员相关接口，银行划扣相关接口
'''
import datetime
import copy
import uuid
import pandas as pd
from enum import Enum
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from server.pao_python.pao.data import string_to_date, date_to_string,get_cur_time
from ...service.common import get_info,operation_result
from ...service.buss_pub.bill_manage import BillManageService, OperationType, Status, TypeId
from ...models.financial_manage import FinancialBook, FinancialAccount, FinancialRecord, FinancialBill, FinancialReceivableProcess, FinancialAccountRecord
from ...models.service_manage import ServiceOrder
from server.pao_python.pao.data import dataframe_to_list, process_db
from ...service.mongo_bill_service import MongoBillFilter
from ...service.common import get_current_user_id,get_current_organization_id
from ..constant import AccountType,AccountStatus,PayStatue
from django.shortcuts import reverse, redirect, render
from ...pao_python.pao.remote import JsonRpc2Error
from ...service.constant import PayStatue,PayType
# from django.db import models
import xlwt
import os
from io import BytesIO
from django.http import HttpResponse
import tablib
# import flask_excel
import flask_excel as excel
from pyexcel_xls import save_data
from collections import OrderedDict
import base64
import numpy as np
class BillType(Enum):
    '''账单类型枚举'''
    Bank_deduction = '银行划账'
    Scene_pay = '现场缴费'


class FinancialAccountObject():
    '''财务账户对象'''

    def __init__(self, name, user_id, agent_user_id, account_status,pay_squence,account_type,extend_info,balance):
        '''构造函数'''
        # 账户名
        self.name = name
        # 所属经济主体id
        self.user_id = user_id
        # 代管经济主体id
        self.agent_user_id = agent_user_id
        # 账户状态
        self.account_status = account_status
        # 付款顺序号
        self.pay_squence = pay_squence
        # 账户类型
        self.account_type = account_type
        # 扩展字段
        self.extend_info = extend_info
        # 余额
        self.balance = balance

    def to_dict(self):
        return self.__dict__

class FinancialTable:
    PT_Financial_Receivable_Process = 'PT_Financial_Receivable_Process'
    PT_Financial_Account = 'PT_Financial_Account'    
    PT_Financial_Account_Record = 'PT_Financial_Account_Record'
    PT_Financial_Account = 'PT_Financial_Account'

class FinancialAccountService(MongoService):
    '''财务管理服务'''
    book_id = '16e726be-b405-11e9-9f09-983b8f0bcd67'

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd,inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_server = BillManageService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd,self.inital_password, self.session)

    def get_unpay_account_list(self, org_list, condition):
        '''收费员通过姓名和身份证号码查找对应的待收款账单'''
        keys = ['name', 'id_card']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('pay_info.name') == values['name'])
                           & (C('pay_info.id_card') == values['id_card'])
                           & (C('bill_type') == BillType.Scene_pay.value)
                           & (C('pay_state') == PayStatue.ready_pay)
                           & (C('organization_id').inner(org_list)))
        _filter_sum = copy.deepcopy(_filter)
        _filter_sum.group(None, [{'amount': self.ao.summation('$amount')}])\
                   .add_fields({'item': '合计'})
        _filter.unwind('bill_detail')\
               .project({'item': '$bill_detail.item', 'amount': '$bill_detail.amount', '_id': 0, 'id': 1})
        res = self.query(_filter, FinancialBill().name)
        res1 = self.query(_filter_sum, FinancialBill().name)
        if len(res1) > 0:
            res.append(res1[0])
        return res

    def get_need_pay_account_list(self, org_list, condition):
        '''收费员通过姓名和身份证号码查找对应的待付款账单'''
        res = 'Fail'
        return res

    def complete_pay_account(self, datas):
        '''收费员完成收款操作，入参为：长者名称：name,长者身份证id：id_card，金额amount，付款方式pay_type'''
        res = 'Fail'
        # 当前登录账号user_id
        # current_user_id = get_current_user_id(self.session)
        # 当前账号所属组织机构id
        current_org_id = get_current_organization_id(self.session)
        # 代管账户id
        agent_account = ''
         # 通过长者名称和身份证号找到user_id
        _filter_org = MongoBillFilter()
        _filter_org.match_bill((C('id') == current_org_id))\
            .project({'_id': 0})
        res_org = self.query(_filter_org, 'PT_User')
        if len(res_org)>0 and 'agent_account' in res_org[0].keys() :
            agent_account = res_org[0]['agent_account']
        paytype = datas['pay_type']
        amount = datas['amount']
        # 通过长者名称和身份证号找到user_id
        _filter = MongoBillFilter()
        _filter.match_bill((C('name') == datas['name'])
                           & (C('id_card') == datas['id_card']))\
            .project({'_id': 0})
        res = self.query(_filter, 'PT_User')
        if len(res) > 0:
            # 长者user_id
            user_id = res[0]['id']
            # 账户表
            account_data = {}
            # 查找长者真实账户id
            _filter = MongoBillFilter()
            _filter.match_bill((C('user_id') == user_id)
                                &(C('account_type') == AccountType.account_real))\
                .project({'_id': 0})
            res_real = self.query(_filter, FinancialAccount().name)
            # 修改账户信息：余额
            _filter = MongoBillFilter()
            _filter.match_bill((C('user_id') == user_id)
                                &(C('account_type') == AccountType.account_recharg_wel))\
                .project({'_id': 0})
            res_current = self.query(_filter, FinancialAccount().name)
            if len(res_current)>0 and len(res_real)>0:
                pay_account = res_real[0]['id']
                account_data = res_current[0]
                account_data['balance'] = float(account_data['balance']) + amount
                
                # 账户出入记录：记录一条
                # 账户出入记录
                account_record_data = {'account_id':account_data['id'],'amount':amount,'balance':float(account_data['balance']),'abstract':'充值收款','date':datetime.datetime.now()}
                account_record = get_info(account_record_data,self.session)

                 
                # 账户收付款过程记录：1付款方：付款方为长者，账户Id为长者的真实账户id。2收款方：收款方为机构，账户Id默认为机构的代管账户
                # 账户收付款过程记录
                receivable_process_data={'financial_id':str(uuid.uuid1()),'receiver_account_id':agent_account,'pay_account_id':pay_account,'amount':amount,'pay_status':PayStatue.success,'pay_type':paytype,'date':datetime.datetime.now()}
                receivable_process = get_info(receivable_process_data,self.session)
                bill_id = self.bill_manage_server.add_bill(OperationType.update.value, TypeId.financial.value, account_data, FinancialAccount().name)
                bill_id = self.bill_manage_server.add_bill(
                        OperationType.add.value, TypeId.financial.value, [receivable_process, account_record], [FinancialReceivableProcess().name, FinancialAccountRecord().name])
                            
                if bill_id:
                    res = 'Success'
            else:
                res='找不到当前登录用户所属组织机构的账户信息。'
        else:
            res = '找不到改长者账户信息，请先新增长者。'
        return res

    def add_service_settlement_data(self, data):
        '''增加服务商结算账单数据，服务商为收款方'''
        res = 'Fail'
        
        return res

    def __merge_data(self, data):
        tep_df = pd.DataFrame(data)
        res_df = tep_df.groupby(['user_id', 'name', 'card_id'])[
            ['amount']].sum()
        res_list = dataframe_to_list(pd.DataFrame(
            list(res_df.index), columns=['user_id', 'name', 'card_id']))
        for i in res_list:
            i['amount'] = 0
            i['bill_detail'] = []
            for j in data:
                if i['user_id'] == j['user_id'] and i['name'] == j['name'] and i['card_id'] == j['card_id']:
                    i['amount'] = i['amount']+j['amount']
                    i['bill_detail'].append(
                        {'item': j['item'], 'amount': j['amount']})
        return res_list

    def __add_type_data(self, detail_data, pay_state, bill_type, pay_type=None):
        '''增加插入账单时需的类型相关数据'''
        res = []
        bill_id = str(uuid.uuid1())
        date = datetime.datetime.now()
        for i in detail_data:
            i['bill_id'] = bill_id
            i['pay_state'] = pay_state
            i['bill_type'] = bill_type
            i['date'] = date
            if pay_type != None:
                i['pay_type'] = pay_type
            res.append(i)
        return res

    def add_elder_settlement_data(self, detail_data):
        '''增加老人结算账单(需到收费员处缴纳)数据'''
        res = 'Fail'
        
        return res

    def add_bank_charge_data(self, paying_data_list):
        '''
        业务系统发送扣费信息，财务系统根据代付顺序进行扣款，若直接通过虚拟账户扣款成功的，
        则直接进行相关的账户余额变动操作，若扣款失败需要通过银行进行划扣，需要银行划扣的账单，
        存入收入款过程记录表，账单号为空，支付方式银行划扣
        paying_data_list  {list}   扣款划账信息list
        [{
            'pay_id':'付款方id',
            'receive_id':'收款方id',
            'amount':'金额',
            'abstract':'摘要'
        },]
        '''
        res = 'Fail'
        for paying_data in paying_data_list:
            if paying_data.get('pay_id') and paying_data.get('receive_id'):
                # 根据pay_id和receive_id找到对应的user信息
                _filter = MongoBillFilter()
                _filter.match_bill(C('id') == paying_data.get('pay_id')).project({'_id':0})
                res_pay = self.query(_filter,'PT_User')
                # 初始化付款顺序为真实账户
                pay_sequence_list = [AccountType.account_real]
                _filter_receive = MongoBillFilter()
                _filter_receive.match_bill(C('id') == paying_data.get('receive_id'))\
                    .lookup('PT_Financial_Agent_Pay_Sequence','id','user_id','pay_sequence_info')\
                    .project({'_id':0,'pay_sequence_info._id':0})
                res_receive = self.query(_filter_receive,'PT_User')
                if len(res_pay)>0 and len(res_receive)>0:
                    if res_receive[0].get('pay_sequence_info'):
                        #获取收款方的付款账户类型顺序
                        pay_sequence_list = res_receive[0].get('pay_sequence_info')[0].get('agent_pay_sequence')
                    # 判断付款账户类型顺序的第一个类型是否为机构储值账户
                    if pay_sequence_list[0] == AccountType.account_recharg_wel:
                        # 查找付款方的机构储值账户和收款方的主账户main_account
                        _filter_pay_account = MongoBillFilter()
                        _filter_pay_account.match_bill((C('user_id') == res_pay[0].get('id')) & (C('account_type') == AccountType.account_recharg_wel) & (C('account_status') == AccountStatus.normal))\
                            .project({'_id':0})
                        res_pay_account = self.query(_filter_pay_account,'PT_Financial_Account')
                        _filter_receive_account = MongoBillFilter()
                        _filter_receive_account.match_bill((C('id') == res_receive[0].get('main_account')))\
                            .project({'_id':0})
                        res_receive_account = self.query(_filter_pay_account,'PT_Financial_Account')
                        if res_pay_account and res_receive_account:
                            # 判断付款方账户余额是否充足
                            if float(res_pay_account[0].get('balance')) >= float(paying_data.get('amount')):
                                # 若账户余额充足
                                new_account_data_pay = {
                                'id':res_pay_account[0].get('id'),
                                    'balance':float(res_pay_account[0].get('balance')) - float(paying_data.get('amount'))
                                }
                                new_account_data_receive = {
                                'id':res_receive_account[0].get('id'),
                                    'balance':float(res_receive_account[0].get('balance')) + float(paying_data.get('amount'))
                                }
                                # 付款成功，更新余额
                                self.bill_manage_server.add_bill(OperationType.update.value,
                                                        TypeId.account.value, [new_account_data_pay,new_account_data_receive], 'PT_Financial_Account')
                                # 收付款过程记录
                                process_record_data = {
                                    'financial_id':str(uuid.uuid1()),
                                    'pay_account_id':res_pay_account[0].get('id'),
                                    'receiver_account_id':res_receive[0].get('main_account') if res_receive[0].get('main_account') else None,
                                    'amount':float(paying_data.get('amount')),
                                    'abstract':paying_data.get('abstract'),
                                    'pay_status':PayStatue.success,
                                    'pay_type':PayType.recharge_wel,
                                    'date':datetime.datetime.now()
                                }
                                # 付款方账户出入记录
                                account_record_data_pay = {
                                    'account_id':res_pay_account[0].get('id'),
                                    'amount':float(paying_data.get('amount')),
                                    'balance':new_account_data_pay.get('balance'),
                                    'abstract':paying_data.get('abstract'),
                                    'date':datetime.datetime.now()
                                }
                                # 收款方账户出入记录
                                account_record_data_receive = {
                                    'account_id':res_receive[0].get('main_account') if res_receive[0].get('main_account') else None,
                                    'amount':float(paying_data.get('amount')),
                                    'balance':new_account_data_receive.get('balance'),
                                    'abstract':paying_data.get('abstract'),
                                    'date':datetime.datetime.now()
                                }
                                
                                new_process_record_data = get_info(process_record_data,self.session)
                                new_account_record_data_pay = get_info(account_record_data_pay,self.session)
                                new_account_record_data_receive = get_info(account_record_data_receive,self.session)
                                # 生成收付款过程记录
                                self.bill_manage_server.add_bill(OperationType.add.value,
                                                        TypeId.financialReceivableProcess.value, new_process_record_data, 'PT_Financial_Receivable_Process')
                                # 生成账户出入记录
                                self.bill_manage_server.add_bill(OperationType.add.value,
                                                        TypeId.accountRecord.value, [new_account_record_data_pay,new_account_record_data_receive], 'PT_Financial_Account_Record')
                                res = 'Success'
                            #付款方余额不足
                            else:
                                #查找付款方的真实账户
                                _filter_pay_account_true = MongoBillFilter()
                                _filter_pay_account_true.match_bill((C('user_id') == res_pay[0].get('id')) & (C('account_type') == AccountType.account_real) & (C('account_status') == AccountStatus.normal))\
                                    .project({'_id':0})
                                res_pay_account_true = self.query(_filter_pay_account_true,'PT_Financial_Account')
                                if res_pay_account_true:
                                    # 收付款过程记录
                                    process_record_data = {
                                        'financial_id':'',
                                        'pay_account_id':res_pay_account_true[0].get('id'),
                                        'receiver_account_id':res_receive[0].get('main_account') if res_receive[0].get('main_account') else None,
                                        'amount':float(paying_data.get('amount')),
                                        'abstract':paying_data.get('abstract'),
                                        'pay_status':PayStatue.ready_pay,
                                        'pay_type':PayType.bank,
                                        'date':datetime.datetime.now()
                                    }
                                    new_process_record_data = get_info(process_record_data,self.session)
                                    # 生成收付款过程记录
                                    self.bill_manage_server.add_bill(OperationType.add.value,
                                                            TypeId.financialReceivableProcess.value, new_process_record_data, 'PT_Financial_Receivable_Process')
                                res = 'Success'
                    # 付款账户类型顺序的第一个类型不是机构储值账户，则归为银行划账
                    else:
                        # 查找付款方的真实账户
                        _filter_pay_account = MongoBillFilter()
                        _filter_pay_account.match_bill((C('user_id') == res_pay[0].get('id')) &(C('account_status') == AccountStatus.normal) & (C('account_type') == AccountType.account_real)).project({'_id':0})
                        res_pay_account = self.query(_filter_pay_account,'PT_Financial_Account')
                        if res_pay_account:
                            card_number = res_pay_account[0]['extend_info'].get('card_number')
                            #  收付款过程记录
                            process_record_data = {
                                    'financial_id':'',
                                    'pay_account_id':res_pay_account[0].get('id'),
                                    'receiver_account_id':res_receive[0].get('main_account') if res_receive[0].get('main_account') else None,
                                    'amount':float(paying_data.get('amount')),
                                    'abstract':paying_data.get('abstract'),
                                    'pay_status':PayStatue.ready_pay,
                                    'pay_type':PayType.bank if card_number and card_number !='' else PayType.other,
                                    'date':datetime.datetime.now()
                                }
                            new_process_record_data = get_info(process_record_data,self.session)
                            #  生成收付款过程记录
                            self.bill_manage_server.add_bill(OperationType.add.value,
                                                    TypeId.financialReceivableProcess.value, new_process_record_data, 'PT_Financial_Receivable_Process')
                        res = "Success"
                            
        return res
        
    def get_bank_unreconciliation_list(self, org_list, condition, page, count):
        '''获取银行扣款单(未进行划扣），现改为获取所有类型的未扣账单'''
        keys = ['user_name', 'financial_id', 'date', 'receiver_name', 'pay_status', 'pay_type']
        if 'pay_type' in condition.keys() and condition['pay_type'] == '全部':
            del condition['pay_type']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        start = end = N()
        if bool(1-isinstance(values['date'], N)):
            start = values['date'][0]
            end = values['date'][1]
        if 'financial_id' in condition.keys():
            if condition['financial_id'] == '':
                _filter.match((C('financial_id') == None) | (C('financial_id') == ''))
            else:
                _filter.match((C('financial_id').like(values['financial_id'])))
        _filter.match_bill((C('organization_id').inner(org_list)) & (C('pay_type') == values['pay_type'])) \
               .inner_join_bill('PT_Financial_Account', 'pay_account_id', 'id', 'pay') \
               .inner_join_bill('PT_Financial_Account', 'receiver_account_id', 'id', 'receiver') \
               .inner_join_bill('PT_User', 'pay.user_id', 'id', 'user') \
               .match(
                   (C('pay_status') == values['pay_status'])
                   & (C('user.name').like(values['user_name']))
                   & (C('receiver.extend_info.card_name').like(values['receiver_name']))
                   & (C('date')>as_date(start))
                   & (C('date')<as_date(end))
                   )\
               .project({'_id':0,'pay_acount._id':0,'receiver_acount._id':0,'user._id':0,'receiver._id':0,'pay._id':0})
        res = self.page_query(_filter, FinancialTable.PT_Financial_Receivable_Process, page, count)
        return res

    def get_bank_reconciliation_list(self, org_list, condition, page, count):
        '''获取银行扣款单(已进行划扣）'''
        res = 'Fail'
        return res

    

    def exprot_excel(self, financial_id, page, size):
        _filter = self.__get_bank_data([financial_id])
        if not financial_id :  # 导出全部没有单号的数据,为数据添加单号，并更新到数据库，代表账单已经导出过
            financial_id = str(uuid.uuid1())
            _filter_add = MongoBillFilter()
            _filter_add.match_bill((C('financial_id') == None) | (C('financial_id') == ''))\
                    .add_fields({'financial_id': financial_id})\
                   .project({'_id': 0, 'id': 1, 'financial_id': 1})
            res = self.query(_filter_add, FinancialTable.PT_Financial_Receivable_Process)
            if len(res):
                bill_id = self.bill_manage_server.add_bill(OperationType.update.value, TypeId.financial.value, res, FinancialTable.PT_Financial_Receivable_Process)
                if not bill_id:
                    raise JsonRpc2Error(-36106, "下载失败")
            else:
                raise JsonRpc2Error(-36107, "暂无数据可下载")
            _filter = self.__get_bank_data([financial_id])
        _filter.group(
                    {
                        # '长者姓名':'$user.name',
                        '付款方姓名': '$pay.extend_info.card_name',
                        '付款方账号': '$pay.extend_info.card_number',
                        '收款方姓名': '$receiver.extend_info.card_name',
                        '收款方账号': '$receiver.extend_info.card_number',
                        '账单号': '$financial_id',
                        '状态':'待付款'

                    },
                    [{'金额':self.ao.summation('$amount')}])\
                .project({
                    '_id': 0,
                    '账单号': 1, '长者姓名': 1, '身份证': 1, '付款方姓名': 1,'付款方账号': 1,'收款方姓名': 1,   '收款方账号': 1, '金额': 1,'状态':1
                    })
        res = self.page_query(_filter, FinancialTable.PT_Financial_Receivable_Process, page, size)
        if not len(res['result']):
           raise JsonRpc2Error(-36105,'暂无数据可下载')
        return res

    def upload_excel_manage(self,file_data):
        bill_id = False
        bill_id_recode = True
        bill_id_acount = True
        pd_file = pd.DataFrame(file_data)
        pd_file.rename(columns=
            {
            '账单号':'financial_id',
            '付款方姓名': 'pay_name',
            '付款方账号': 'pay_number',
            '收款方姓名': 'receiver_name',
            '收款方账户': 'receiver_number',
            '状态':'pay_status',
            '金额':'amount'
            }, inplace=True)
        # 获取excel表格内容的账单号
        financial_id_list = pd_file['financial_id'].drop_duplicates().tolist()
        data_file = dataframe_to_list(pd_file)
        _filter = self.__get_filter(financial_id_list)
        _filter.group({
            'financial_id': '$financial_id',
            'pay_number': '$pay.extend_info.card_number',
            'pay_balance': '$pay_balance',
            'receiver_balance':'$receiver_balance',
            'pay_account_id':'$pay_account_id',
            'receiver_account_id':'$receiver_account_id'
            }, [{'amount': self.ao.summation('$amount')}]) \
                .project({
                    '_id': 0, 
                    'pay_number': 1, 
                    'id': 1,
                    'amount': 1,
                    'financial_id': 1,
                    'pay_account_id': 1,
                    'receiver_account_id': 1
                })
        res = self.query(_filter, FinancialTable.PT_Financial_Receivable_Process)
        # 判断导入内容数量与查询结果是否相等，若不相等，则存在导入数据重复
        if len(res) and (len(res) != len(file_data)):
            raise JsonRpc2Error(-36102,'导入内容存在已导过的数据')
        if len(res):
            success_card_num = []
            fail_card_num = []
            for i,y in enumerate(data_file): #将导入内容与查询结果内容进行对比是否完全相等
                i = i+1
                for x in res:
                    try: # 核对金额,账单号,付款卡号是否一致
                        if str(y['pay_number']) == x['pay_number'] and y['amount'] == x['amount'] and y['financial_id'] == x['financial_id'] and y['pay_status']:
                            pram = {'card_number': x['pay_number'], 'amount': x['amount'], 'pay_account_id': x['pay_account_id'], 'receiver_account_id': x['receiver_account_id']}
                            # 将上传内容根据划账成功/失败区分开来
                            success_card_num.append(x['pay_number']) if y['pay_status'] == PayStatue.success else fail_card_num.append(x['pay_number'])
                    except:
                        raise JsonRpc2Error(-36109,'收款方卡号'+str(y['pay_number'])+'所在行数据异常，请检查上传内容是否正确')
                if len(success_card_num) + len(fail_card_num) != i:# 若当前导入数据行与查询结果没有匹配到，说明当前导入行字段内容存在错误
                    raise JsonRpc2Error(-36109,'收款方卡号'+str(y['pay_number'])+'所在行数据异常，请检查上传内容是否正确')
            result = [{'status': PayStatue.success, 'value': success_card_num}, {'status': PayStatue.fail, 'value': fail_card_num}]
            data = []
            recode = []
            account_dict = {}
            balance = 0
            for z in result: # 
                if len(z['value']): #更新账单的银行划扣结果  
                    _filter_new = self.__get_filter(financial_id_list)    
                    _filter_new.match(C('pay_number').inner(z['value'])) \
                                .add_fields({'pay_status': z['status'],'abstract':'银行划账'+z['status']})
                    if z['status'] == PayStatue.fail:
                        _filter_new.add_fields({'financial_id': None,})
                    if z['status'] == PayStatue.success:
                        # 如果划扣成功，生成收付款过程记录
                        recode_res = self.query(_filter_new, FinancialTable.PT_Financial_Receivable_Process)
                        account_dict = {'id': recode_res[0]['receiver']['id'], 'balance': 0}
                        balance = recode_res[0]['receiver']['balance']
                        for x in recode_res:
                            date = get_cur_time()
                            # 付款方记录
                            pay_recode = {'account_id': x['pay_account_id'], 'amount': -x['amount'], 'balance': x['pay']['balance'], 'abstract': PayType.bank, 'date': date}
                            # 收款方记录
                            balance = balance + x['amount']  # 平台余额
                            account_dict['organization_id'] = x['id']
                            receiver = {'account_id': x['receiver_account_id'], 'amount': x['amount'], 'balance': balance, 'abstract': PayType.bank, 'date': date}
                            # account_list.append({'id':x['receiver']['id'],'balance':balance})
                            recode.append(get_info(pay_recode,self.session))
                            recode.append(get_info(receiver, self.session))
                    account_dict.update(balance=balance)
                    _filter_new.project({'pay': 0, 'user': 0, 'receiver': 0, 'pay_number': 0})
                    # 账单更新数据收集
                    import_res = self.query(_filter_new, FinancialTable.PT_Financial_Receivable_Process)
                    data = data + import_res
            # 更新账单
            bill_id = self.bill_manage_server.add_bill(OperationType.update.value, TypeId.financialReceivableProcess.value, data, FinancialTable.PT_Financial_Receivable_Process)
            if len(recode): # 划账成功的,新增收付款过程记录
                bill_id_recode = self.bill_manage_server.add_bill(OperationType.add.value, TypeId.accountRecord.value, recode, FinancialTable.PT_Financial_Account_Record)
                bill_id_acount = self.bill_manage_server.add_bill(OperationType.update.value, TypeId.account.value, account_dict, FinancialTable.PT_Financial_Account)
            if not (bill_id and bill_id_recode):
                raise JsonRpc2Error(-36102,'导入失败')
        else:
            raise JsonRpc2Error(-36111,'数据库不存在导入的内容,或者已划账成功')
        return '导入成功'

    def update_unbank_reconciliation(self, condition):
       bill_id = self.bill_manage_server.add_bill(OperationType.update.value,
                                                        TypeId.financialReceivableProcess.value, condition, FinancialTable.PT_Financial_Receivable_Process)
       return operation_result(bill_id)

    def __get_filter(self,financial_id_list):
        _filter = self.__get_bank_data(financial_id_list)
        _filter.match_bill(C('pay_status') != PayStatue.success) \
                .add_fields({
                    'pay_number': '$pay.extend_info.card_number',
                    'pay_balance': '$pay.balance',
                    'receiver_balance':'$receiver.balance',
                    })
        return _filter
        
    def __get_bank_data(self, financial_id):
       _filter = MongoBillFilter()
       _filter.match_bill(C('financial_id').inner(financial_id)) \
               .inner_join_bill('PT_Financial_Account', 'pay_account_id', 'id', 'pay') \
                .inner_join_bill('PT_Financial_Account', 'receiver_account_id', 'id', 'receiver') \
                .inner_join_bill('PT_User', 'pay.user_id', 'id', 'user')
       print(_filter.filter_objects)
       return _filter
       
